<?
require_once("db/db.php");

header("Pragma: no-cache"); 
header("Expires: 0"); 	

$outputType = isset($_GET['OutputType']) ? $_GET['OutputType'] : 'JSON';
switch($outputType)
{
	case 'JSON':
		header('Content-type: application/x-javascript');  // output as JSON
		break;
	case 'CSV':
		header("Content-type: application/octet-stream"); 
		header("Content-Disposition: attachment; filename=SearchQuery.csv"); 
		break;
	default:
}

// Get the connection string
$XMLFile = "/home/assclap/config/real_estate.quickdata.config.xml"; //$_GET['XMLFile'];

if(!isset($_GET['QueryID'])) 
	die("query failed\nQueryID not set");
else
	$QueryID = $_GET['QueryID'];

// Get the connection string
$xml = simplexml_load_file($XMLFile);
$Definition = $xml->xpath("//ConnectionString");
$conn = (string)$Definition[0]['Value'];

// Get the query fields	
$Definition = $xml->xpath("//SearchQuery[@ID=\"{$QueryID}\"]");
$FIELDS = (string)$Definition[0]['Fields'];
$FROM = (string)$Definition[0]['From'];
$fromStr = '';
$WHERE = array();
$whereStr = '';
$ORDER_BY = (string)$Definition[0]['Order'];
$CONJUNCTION = (string)$Definition[0]['Conjunction'];
if(strlen($CONJUNCTION) == 0) $CONJUNCTION = 'AND';

// Get the query parameters and replace the tokens 
$Definition = $xml->xpath("//SearchQuery[@ID=\"{$QueryID}\"]/Parameter");
for($i=0; $i < sizeof($Definition); $i++)
{
	$field = (string)$Definition[$i]['id'];
	if(!isset($_GET[$field])) 
		die("Parameter \"$field\" defined in XML was not found in " . '$_GET');
	else
	{
		// addslashes protects against sql injection via closequotes
		$value = addslashes($_GET[$field]);
		if(strlen($value))
		{
			@$whereStr = (string)$Definition[$i]['whereStr'];
			@$fromStr = (string)$Definition[$i]['fromStr'];
			@$type = (string)$Definition[$i]['type'];
			@$condition = (string)$Definition[$i]['condition'];
			
			if(strlen($whereStr))
				if($type == 'array') {
					//it's an array, $value should be a comma seperated string
					if(strlen($value))
					{
						$condition = $condition ? " $condition " : " OR ";
						$valuelist = split(',', $value);
						$whereList = array();
						foreach ($valuelist as $value)
						{
							$whereList[] = str_replace('$' . $field . '$', $value, $whereStr);
						}
						$WHERE[] = ' (' . join($condition, $whereList) . ') ';
					}
				}
				else // It's just a regular string/numeric value
					$WHERE[] =  ' (' . str_replace('$' . $field . '$', $value, $whereStr)  . ') ';
					
			if(strlen($fromStr)) 
				$FROM .=  " $fromStr";
		}
	}
}
// Build the sql	
$sql = "SELECT DISTINCT $FIELDS FROM $FROM";
$sql .= (count($WHERE) ? " WHERE " . join(" $CONJUNCTION ", $WHERE) : '');

// connect and grab the data
$db = new DBConnection($conn);
$r = $db->CreateQuery($sql);

$objReturn = new QueryAndData();
$objReturn->SQL = $sql;
//$objReturn->Rows = $rows;

switch($outputType)
{
	case 'JSON':
		while($row = $r->FetchObject())
			$objReturn->Rows[] = $row;
		echo json_encode($objReturn);
		break;
	case 'CSV':
		while($row = $r->FetchRow())
			echo implode(', ', $row) . "\n";
			
		break;
	default:
}
	
	
class QueryAndData
{
	public $SQL;
	public $Rows;
}
?>
